import os.path
import random
from abc import abstractmethod

import pyautogui

from run import BAG, NOTIFY, PANO, GET, HEAD


class Rect:
    def __init__(self, x, y, w, h, fix_pixes=3):
        self.rect = (
            self.x,
            self.y,
            self.w,
            self.h,
        ) = x, y, w, h
        self.fix_pixes = fix_pixes

    def point(self):
        """返回目标位置点击点"""
        return (
            random.randint(
                self.x + self.fix_pixes,
                self.x + self.w - self.fix_pixes
            ),
            random.randint(
                self.y + self.fix_pixes,
                self.y + self.h - self.fix_pixes
            )
        )

    def offset(self, offset: tuple[int, int], w, h, fix_pixes=None):
        ox, oy = offset
        fix_pixes = fix_pixes or self.fix_pixes
        return Rect(self.x + ox,
                    self.y + oy,
                    w, h, fix_pixes)


class Region(Rect):
    """按钮查找区域"""

    def __init__(self, x, y, w, h, fix_pixes=3):
        super().__init__(x, y, w, h, fix_pixes)

    @abstractmethod
    def target(self):
        """匹配目标图片"""
        pass

    @abstractmethod
    def confidence(self):
        return 0.7

    def point(self):
        """返回目标位置点击点"""
        return self.match().point()

    def offset(self, offset: tuple[int, int], w, h, fix_pixes=None):
        return self.match().offset(offset, w, h,
                                   fix_pixes or self.fix_pixes).point()

    def match(self):
        """匹配目标位置"""
        img_path = os.path.join('resource', self.target())
        target = pyautogui.locateOnScreen(
            img_path,
            region=self.rect,
            confidence=self.confidence(),
        )
        return Rect(*target, self.fix_pixes)


class Tree(Region):
    def target(self):
        return 'tree.png'

    def __init__(self):
        super().__init__(*BAG)


class Food(Region):
    def confidence(self):
        return 0.65

    def target(self):
        return 'food.png'

    def __init__(self):
        super().__init__(*BAG)


class FoodFull(Food):
    def confidence(self):
        return .85

    def target(self):
        return 'food_full.png'


class Notify(Region):
    def target(self):
        return 'treed.png'

    def __init__(self):
        super().__init__(*NOTIFY)


class Get(Region):
    def target(self):
        return 'get.png'

    def __init__(self):
        super().__init__(*GET)


class ErrNumber(Region):
    def target(self):
        return 'number.png'

    def __init__(self):
        super().__init__(*GET)


class Eat(Region):
    def target(self):
        return 'eat_pano.png'

    def __init__(self):
        super().__init__(*PANO, fix_pixes=1)


class Head(Region):
    def confidence(self):
        return .75

    def target(self):
        return 'tree_target.png'

    def __init__(self):
        super().__init__(*HEAD)
